#include "server.h"
#include "qdatetime.h"
#include "qdir.h"
#include "qtcpsocket.h"
#include <QFile>
#include <QTimer>
Server::Server(const QString &saveDir, QObject *parent)
    : QTcpServer{parent},m_saveDir(saveDir)
{
    QDir dir(m_saveDir);
    if (!dir.exists()) {
        dir.mkpath(".");  // 确保目录存在
    }
}

void Server::incomingConnection(qintptr socketDescriptor)
{
    QTcpSocket *socket = new QTcpSocket(this);
    connect(socket, &QTcpSocket::readyRead, this, &Server::readClient);
    connect(socket, &QTcpSocket::disconnected, this, &Server::discardClient);

    socket->setSocketDescriptor(socketDescriptor);
    qInfo() << "New connection from:" << socket->peerAddress().toString();
}


void Server::readClient()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());


    QByteArray data = socket->readAll();
    qDebug() << "收到数据大小:" << data.size() << "字节";

    // 验证数据完整性
    if (data.size() >= 4 && data.startsWith("FLST") && data.endsWith("FEND")) {
        qDebug()<<"验证";
        saveReceivedFile(data);
        socket->write("SUCCESS: 文件接收完成");
    } else {
        socket->write("ERROR: 无效文件格式");
    }

}

void Server::discardClient()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (socket) {
        socket->deleteLater();
        qInfo() << "Client disconnected";
    }
}

void Server::saveReceivedFile(const QByteArray &data)
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss");
    QString filename = m_saveDir + "/received_" + timestamp + ".dat";

    QFile file(filename);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(data);
        file.close();
        qInfo() << "File saved to:" << filename;

        // 解析.dat文件
        QDataStream in(data);
        in.setVersion(QDataStream::Qt_6_5);
        // 2.1 检查文件头
        char header[5] = {0};
        in.readRawData(header, 4);
        qDebug() << "文件头:" << header << (strcmp(header, "FLST") == 0 ? "(有效)" : "(无效)");
        // 2.3 读取目录路径
        QString dirPath;
        in >> dirPath;
        qDebug() << "目录路径:" << dirPath;

        // 2.4 读取文件数量
        quint32 fileCount;
        in >> fileCount;
        qDebug() << "包含文件数:" << fileCount;
        // 2.5 读取每个文件名
        for (quint32 i = 0; i < fileCount; ++i) {
            QString fileName;
            in >> fileName;
            qDebug() << QString("文件%1:").arg(i+1, 2) << fileName;
        }
        // 2.6 检查文件尾
        char footer[5] = {0};
        in.readRawData(footer, 4);
        qDebug() << "文件尾:" << footer << (strcmp(footer, "FEND") == 0 ? "(有效)" : "(无效)");
        // 2.7 检查数据完整性
        qDebug() << "剩余未读字节:" << data.size() - in.device()->pos();
        qDebug() << "===== 解析完成 =====\n";
    } else {
        qWarning() << "Failed to save received file";
    }
}
